'use client'

import { useState, useRef } from 'react'
import {
  Card, Input, Button, Typography, Timeline, Descriptions, 
  Image, Row, Col, Space, message, Divider, QRCode, Modal,
  Spin, Alert, Tabs
} from 'antd'
import {
  QrcodeOutlined, SearchOutlined, EnvironmentOutlined,
  CalendarOutlined, TruckOutlined, SafetyOutlined,
  ShopOutlined, HomeOutlined, ScanOutlined,
  InfoCircleOutlined, FileTextOutlined, CarOutlined
} from '@ant-design/icons'
import { request } from '@/utils/request'
import { API_ENDPOINTS } from '@/utils/constants'

const { Title, Text, Paragraph } = Typography
const { Search } = Input
const { TabPane } = Tabs

interface TraceabilityInfo {
  id: number
  batchNumber: string
  productId: number
  productName: string
  fishingVessel: string
  fishingLocation: string
  fishingCoordinates: string
  fishingDate: string
  fishingMethod: string
  processingFacility: string
  processingDate: string
  freezingMethod: string
  qualityCertificate: string
  inspectionReport: string
  qrCode: string
  qrCodeUrl: string
  transportCompany: string
  transportTemperature: string
  createdAt: string
}

export default function TracePage() {
  const [traceInfo, setTraceInfo] = useState<TraceabilityInfo | null>(null)
  const [loading, setLoading] = useState(false)
  const [searchValue, setSearchValue] = useState('')
  const [qrModalVisible, setQrModalVisible] = useState(false)
  const [activeTab, setActiveTab] = useState('1')
  const fileInputRef = useRef<HTMLInputElement>(null)

  const handleSearch = async (value: string) => {
    if (!value.trim()) {
      message.warning('请输入批次号或扫描二维码')
      return
    }

    setLoading(true)
    try {
      const response = await request.get(`${API_ENDPOINTS.TRACE.QUERY}/batch/${value.trim()}`)
      if (response.code === 200) {
        setTraceInfo(response.data)
        message.success('查询成功')
      } else {
        setTraceInfo(null)
        message.error(response.message || '未找到相关溯源信息')
      }
    } catch (error: any) {
      setTraceInfo(null)
      message.error(error.message || '查询失败')
    } finally {
      setLoading(false)
    }
  }

  const handleScanQRCode = () => {
    // 模拟扫码功能，实际项目中可以集成设备扫码
    setQrModalVisible(true)
  }

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      // 模拟二维码识别，实际项目中需要使用二维码识别库
      message.info('模拟扫码成功，请输入批次号：BF20241201001')
      setSearchValue('BF20241201001')
      if (fileInputRef.current) {
        fileInputRef.current.value = ''
      }
    }
  }

  const timelineItems = traceInfo ? [
    {
      color: 'blue',
      dot: <ShopOutlined style={{ fontSize: '16px' }} />,
      children: (
        <Card size="small" title="捕捞阶段" bordered={false} style={{ backgroundColor: '#e6f7ff' }}>
          <Descriptions column={1} size="small" bordered>
            <Descriptions.Item label="渔船">{traceInfo.fishingVessel || '未填写'}</Descriptions.Item>
            <Descriptions.Item label="捕捞地点">{traceInfo.fishingLocation || '未填写'}</Descriptions.Item>
            <Descriptions.Item label="坐标">{traceInfo.fishingCoordinates || '未填写'}</Descriptions.Item>
            <Descriptions.Item label="捕捞日期">{traceInfo.fishingDate || '未填写'}</Descriptions.Item>
            <Descriptions.Item label="捕捞方式">{traceInfo.fishingMethod || '未填写'}</Descriptions.Item>
          </Descriptions>
        </Card>
      ),
    },
    {
      color: 'green',
      dot: <HomeOutlined style={{ fontSize: '16px' }} />,
      children: (
        <Card size="small" title="加工阶段" bordered={false} style={{ backgroundColor: '#f6ffed' }}>
          <Descriptions column={1} size="small" bordered>
            <Descriptions.Item label="加工厂">{traceInfo.processingFacility || '未填写'}</Descriptions.Item>
            <Descriptions.Item label="加工日期">{traceInfo.processingDate || '未填写'}</Descriptions.Item>
            <Descriptions.Item label="冷冻方式">{traceInfo.freezingMethod || '未填写'}</Descriptions.Item>
          </Descriptions>
        </Card>
      ),
    },
    {
      color: 'orange',
      dot: <SafetyOutlined style={{ fontSize: '16px' }} />,
      children: (
        <Card size="small" title="质检阶段" bordered={false} style={{ backgroundColor: '#fff7e6' }}>
          <Descriptions column={1} size="small" bordered>
            <Descriptions.Item label="质量证书">
              {traceInfo.qualityCertificate ? (
                <a href={traceInfo.qualityCertificate} target="_blank" rel="noopener noreferrer">
                  <FileTextOutlined /> 查看证书
                </a>
              ) : (
                '未上传'
              )}
            </Descriptions.Item>
            <Descriptions.Item label="检验报告">
              {traceInfo.inspectionReport ? (
                <a href={traceInfo.inspectionReport} target="_blank" rel="noopener noreferrer">
                  <FileTextOutlined /> 查看报告
                </a>
              ) : (
                '未上传'
              )}
            </Descriptions.Item>
          </Descriptions>
        </Card>
      ),
    },
    {
      color: 'purple',
      dot: <CarOutlined style={{ fontSize: '16px' }} />,
      children: (
        <Card size="small" title="运输阶段" bordered={false} style={{ backgroundColor: '#f9f0ff' }}>
          <Descriptions column={1} size="small" bordered>
            <Descriptions.Item label="运输公司">{traceInfo.transportCompany || '未填写'}</Descriptions.Item>
            <Descriptions.Item label="运输温度">{traceInfo.transportTemperature || '未填写'}</Descriptions.Item>
          </Descriptions>
        </Card>
      ),
    },
  ] : []

  return (
    <div style={{ padding: '20px', minHeight: '100vh', background: '#f5f5f5' }}>
      <Title level={2} style={{ textAlign: 'center', marginBottom: '30px' }}>
        <QrcodeOutlined /> 产品溯源查询
      </Title>

      {/* 搜索卡片 */}
      <Card style={{ marginBottom: '20px' }}>
        <div style={{ textAlign: 'center' }}>
          <Title level={4} style={{ marginBottom: '20px' }}>
            请输入批次号或扫描二维码
          </Title>
          <Row justify="center" gutter={[16, 16]}>
            <Col xs={24} sm={16} md={12} lg={8}>
              <Search
                placeholder="请输入批次号（如：BF20241201001）"
                enterButton={
                  <Button type="primary" icon={<SearchOutlined />}>
                    查询
                  </Button>
                }
                size="large"
                value={searchValue}
                onChange={(e) => setSearchValue(e.target.value)}
                onSearch={handleSearch}
                loading={loading}
              />
            </Col>
          </Row>
          
          <div style={{ marginTop: '20px' }}>
            <Space size="large">
              <Button 
                type="primary" 
                icon={<ScanOutlined />} 
                size="large"
                onClick={handleScanQRCode}
              >
                扫描二维码
              </Button>
              <Button 
                icon={<QrcodeOutlined />} 
                size="large"
                onClick={() => document.getElementById('fileInput')?.click()}
              >
                上传二维码图片
              </Button>
              <input
                id="fileInput"
                type="file"
                ref={fileInputRef}
                accept="image/*"
                style={{ display: 'none' }}
                onChange={handleFileUpload}
              />
            </Space>
          </div>
          
          <div style={{ marginTop: '20px' }}>
            <Text type="secondary">
              您可以在产品包装上找到批次号，或扫描产品二维码获取批次号
            </Text>
          </div>
        </div>
      </Card>

      {/* 溯源结果 */}
      {loading && !traceInfo && (
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <Spin size="large" />
          <div style={{ marginTop: '16px' }}>正在查询溯源信息...</div>
        </div>
      )}

      {traceInfo && (
        <Row gutter={[16, 16]}>
          {/* 产品信息 */}
          <Col xs={24} lg={8}>
            <Card title="产品信息" style={{ height: '100%' }}>
              <Descriptions column={1} size="small" bordered>
                <Descriptions.Item label="产品名称">{traceInfo.productName}</Descriptions.Item>
                <Descriptions.Item label="批次号">
                  <Text strong style={{ color: '#1890ff' }}>{traceInfo.batchNumber}</Text>
                </Descriptions.Item>
                <Descriptions.Item label="生产日期">{traceInfo.createdAt}</Descriptions.Item>
              </Descriptions>
              
              {/* 二维码 */}
              {traceInfo.qrCodeUrl && (
                <div style={{ textAlign: 'center', marginTop: '20px' }}>
                  <Title level={5}>产品二维码</Title>
                  <Image
                    width={150}
                    src={traceInfo.qrCodeUrl}
                    alt="产品二维码"
                    style={{ border: '1px solid #d9d9d9', borderRadius: '4px' }}
                  />
                </div>
              )}
              
              {/* 生成二维码 */}
              <div style={{ textAlign: 'center', marginTop: '20px' }}>
                <Title level={5}>分享溯源信息</Title>
                <QRCode 
                  value={`${window.location.origin}/trace?batch=${traceInfo.batchNumber}`} 
                  size={120}
                  bordered
                />
                <div style={{ marginTop: '8px' }}>
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    扫码查看溯源信息
                  </Text>
                </div>
              </div>
            </Card>
          </Col>

          {/* 溯源时间线 */}
          <Col xs={24} lg={16}>
            <Card title="溯源时间线" style={{ height: '100%' }}>
              <Timeline items={timelineItems} />
            </Card>
          </Col>
        </Row>
      )}

      {/* 使用说明 */}
      {!traceInfo && !loading && (
        <Card title="如何查询溯源信息？">
          <Tabs defaultActiveKey="1" onChange={setActiveTab}>
            <TabPane tab={<span><QrcodeOutlined /> 扫码查询</span>} key="1">
              <Row gutter={[32, 32]}>
                <Col xs={24} md={8}>
                  <div style={{ textAlign: 'center' }}>
                    <ScanOutlined style={{ fontSize: '48px', color: '#1890ff', marginBottom: '16px' }} />
                    <Title level={4}>扫描二维码</Title>
                    <Paragraph>
                      在产品包装上找到二维码，使用手机扫描即可查看溯源信息
                    </Paragraph>
                  </div>
                </Col>
                <Col xs={24} md={8}>
                  <div style={{ textAlign: 'center' }}>
                    <QrcodeOutlined style={{ fontSize: '48px', color: '#52c41a', marginBottom: '16px' }} />
                    <Title level={4}>识别结果</Title>
                    <Paragraph>
                      系统将自动识别二维码内容并跳转到溯源详情页面
                    </Paragraph>
                  </div>
                </Col>
                <Col xs={24} md={8}>
                  <div style={{ textAlign: 'center' }}>
                    <InfoCircleOutlined style={{ fontSize: '48px', color: '#fa8c16', marginBottom: '16px' }} />
                    <Title level={4}>查看详情</Title>
                    <Paragraph>
                      查看产品从捕捞、加工、质检到运输的完整溯源信息
                    </Paragraph>
                  </div>
                </Col>
              </Row>
            </TabPane>
            <TabPane tab={<span><SearchOutlined /> 手动查询</span>} key="2">
              <Row gutter={[32, 32]}>
                <Col xs={24} md={8}>
                  <div style={{ textAlign: 'center' }}>
                    <SearchOutlined style={{ fontSize: '48px', color: '#1890ff', marginBottom: '16px' }} />
                    <Title level={4}>找到批次号</Title>
                    <Paragraph>
                      在产品包装上找到批次号标识，通常格式为：BF20241201001
                    </Paragraph>
                  </div>
                </Col>
                <Col xs={24} md={8}>
                  <div style={{ textAlign: 'center' }}>
                    <EnvironmentOutlined style={{ fontSize: '48px', color: '#52c41a', marginBottom: '16px' }} />
                    <Title level={4}>输入查询</Title>
                    <Paragraph>
                      在上方搜索框中输入批次号，点击查询按钮获取溯源信息
                    </Paragraph>
                  </div>
                </Col>
                <Col xs={24} md={8}>
                  <div style={{ textAlign: 'center' }}>
                    <CalendarOutlined style={{ fontSize: '48px', color: '#fa8c16', marginBottom: '16px' }} />
                    <Title level={4}>查看信息</Title>
                    <Paragraph>
                      查看产品的完整溯源信息，确保产品安全可靠
                    </Paragraph>
                  </div>
                </Col>
              </Row>
            </TabPane>
          </Tabs>
        </Card>
      )}

      {/* 扫码模态框 */}
      <Modal
        title="扫描二维码"
        open={qrModalVisible}
        onCancel={() => setQrModalVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setQrModalVisible(false)}>
            取消
          </Button>,
          <Button 
            key="demo" 
            type="primary" 
            onClick={() => {
              setSearchValue('BF20241201001')
              setQrModalVisible(false)
              handleSearch('BF20241201001')
            }}
          >
            模拟扫码结果
          </Button>
        ]}
      >
        <div style={{ textAlign: 'center', padding: '20px' }}>
          <div style={{ 
            border: '2px dashed #1890ff', 
            borderRadius: '8px', 
            padding: '40px', 
            margin: '20px 0'
          }}>
            <QrcodeOutlined style={{ fontSize: '48px', color: '#1890ff' }} />
            <div style={{ marginTop: '16px' }}>
              请将二维码放置在扫描区域内
            </div>
          </div>
          <Alert 
            message="提示" 
            description="在实际应用中，这里会调用设备摄像头进行扫码识别" 
            type="info" 
            showIcon 
          />
        </div>
      </Modal>
    </div>
  )
}